<template>
  <div>
    <div class="card" style="margin-bottom: 5px">
      <el-input clearable @clear="load" style="width: 260px;margin-right: 5px" v-model="data.name"
                placeholder="请输入姓名" :prefix-icon="Search"></el-input>
      <el-input clearable @clear="load" style="width: 260px;margin-right: 5px"
                v-model="data.username" placeholder="请输入账号" :prefix-icon="Search"></el-input>
      <el-button type="primary" @click="load">查询</el-button>
      <el-button @click="reset">重置</el-button>
    </div>
    <div class="card" style="margin-bottom: 5px">
      <el-button type="primary" @click="handleAdd">新增</el-button>
      <el-button type="danger" @click="deleteBatch">批量删除</el-button>
      <el-upload style="display: inline-block;margin-left: 5px"
        action="http://localhost:8080/user/import"
        :show-file-list="false"
        :on-success="handleImportSuccess"
      >
        <el-button type="success" >导入</el-button>
      </el-upload>
      <el-button type="warning" @click="exportData">导出</el-button>
    </div>
    <div class="card" style="margin-bottom: 5px">
      <el-table :data="data.tableDate" style="width: 100%"
                :header-cell-style="{fontWeight:'bold',color:'#333'}"
                @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55%"></el-table-column>
        <el-table-column prop="name" label="姓名"></el-table-column>
        <el-table-column prop="username" label="账号"></el-table-column>
        <el-table-column prop="phone" label="手机号"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="avatar" label="头像">
          <template #default="scope">
            <el-image :preview-src-list="[scope.row.avatar]"
                      :preview-teleported="true"
                      :src="scope.row.avatar"
                      style="width: 40px;height: 40px;border-radius: 50%;display: block"
                      v-if="scope.row.avatar"/>
          </template>
        </el-table-column>
        <el-table-column  label="操作">
          <template #default="scope">
            <el-button type="primary" icon="Edit" circle @click="handleEdit(scope.row)"></el-button>
            <el-button type="danger" icon="Delete" circle @click="del(scope.row.id)"></el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="card">
      <el-config-provider :locale="zhCn">

        <el-pagination background layout="prev,pager, next,sizes,jumper,total"
                       :total="data.total"
                       v-model:page-size="data.pageSize"
                       @size-change="load"
                       :page-size="[5,10,20]"
                       v-model:current-page="data.pageNum"
                       @current-change="load"
                       small>

        </el-pagination>
      </el-config-provider>

    </div>


    <el-dialog v-model="data.formVisible" title="新增信息" width="500" destroy-on-close>
      <el-form ref="formRef" :rules="data.rules" :model="data.form" label-width="80px"
               style="padding: 20px 30px 0 0">

        <el-form-item prop="name" label="姓名">
          <el-input v-model="data.form.name" autocomplete="off" placeholder="请输入姓名"/>
        </el-form-item>
        <el-form-item prop="username" label="账号">
          <el-input v-model="data.form.username" autocomplete="off" placeholder="请输入账号"/>
        </el-form-item>
        <el-form-item prop="phone" label="手机号">
          <el-input v-model="data.form.phone" autocomplete="off" placeholder="请输入手机号"/>
        </el-form-item>
        <el-form-item prop="email" label="邮箱">
          <el-input v-model="data.form.email" autocomplete="off" placeholder="请输入邮箱"/>
        </el-form-item>
        <el-form-item prop="avatar" label="头像">
          <el-upload action="http://localhost:8080/files/upload/"
                     :on-success="handleFileSuccess"
                     :headers="{token :data.user.token}"
                     list-type="picture"
          >
            <el-button type="primary">上传头像</el-button>
          </el-upload>
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="data.formVisible = false">取消</el-button>
          <el-button type="primary" @click="save">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import {Search} from "@element-plus/icons-vue";
import {reactive, ref} from "vue";
import zhCn from 'element-plus/es/locale/lang/zh-cn';
// @ts-ignore
import request from '@/utils/request.js'
import {ElMessage, ElMessageBox} from "element-plus";

const formRef = ref()
const data = reactive({
  user:JSON.parse(localStorage.getItem('code_user')||'{}'),
  name: null,
  username: null,
  formVisible: false,
  form: {},
  rows: [],
  ids: [],
  rules: {
    name: [
      {required: true, message: "请填写姓名", trigger: "blur"},
    ],
    username: [
      {required: true, message: "请填写账号", trigger: "blur"},
    ],
    phone: [
      {required: true, message: "请填写手机号", trigger: "blur"},
    ],
    email: [
      {required: true, message: "请填写邮箱", trigger: "blur"},
    ]
  },
  tableDate: [],
  pageSize: 10,
  pageNum: 1,
  total: 10,
})

const load = () => {
  request.get('user/selectPage', {
    params: {
      pageNum: data.pageNum,
      pageSize: data.pageSize,
      name: data.name,
      username: data.username,
    }

  }).then(res => {
    if (res.code === 200) {
      data.total = res.data.total;
      data.tableDate = res.data.list;
      data.pageNum = res.data.pageNum;
      data.pageSize = res.data.pageSize;
    } else {
      ElMessage.error(res.msg)
    }
  })
}

load()

const reset = () => {
  data.name = null;
  data.username = null;
}
const handleAdd = () => {
  data.formVisible = true;
  data.form = {}
}
const add = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      request.post('user/add', data.form).then(res => {
        if (res.code === 200) {
          data.formVisible = false;
          ElMessage.success('新增成功')
          load()

        } else {
          ElMessage.error(res.msg)
        }
      })
    }
  })
}

const handleEdit = (row) => {
  data.form = JSON.parse(JSON.stringify(row))
  data.formVisible = true;
}

const update = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      request.put('user/update', data.form).then(res => {
        if (res.code === 200) {
          data.formVisible = false;
          ElMessage.success('修改成功')
          load()

        } else {
          ElMessage.error(res.msg)
        }
      })
    }
  })
}

const save = () => {
  data.form.id ? update() : add()
}

const del = (id) => {
  ElMessageBox.confirm('确认删除该数据？', '删除确认', {type: 'warning'}).then(res => {
    request.delete('user/delete/' + id).then(res => {
      if (res.code === 200) {
        ElMessage.success('删除成功')
        load()
      } else {
        ElMessage.error(res.msg)
      }
    })
  }).catch(err => {
  })
}
const handleSelectionChange = (rows) => {
  data.rows = rows;
  data.ids = data.rows.map(v => v.id);
  // console.log(data.rows.map(v => v.id))
  //
  // console.log(data.ids);
  console.log(data.ids)
}
const deleteBatch = () => {
  if (data.rows.length === 0) {
    ElMessage.warning('请选择要删除的数据！')
    return
  }
  ElMessageBox.confirm('确认删除数据？', '删除确认', {type: 'warning'}).then(res => {
    request.delete('user/deleteBatch', {data: data.rows}).then(res => {
      if (res.code === 200) {
        ElMessage.success('批量删除成功')
        load()
      } else {
        ElMessage.error(res.msg)
      }
    })
  }).catch(err => {
  })
}

const exportData = () => {
  window.open(`http://localhost:8080/user/export?username=${data.username === null ? '' : data.username}`
  +`&name=${data.name === null ? '' : data.name}`
  +`&ids=${data.ids.join(',')}`
    +`&token=${data.user.token}`
  )

}

const handleImportSuccess = (res) => {
  if (res.code === 200) {
    ElMessage.success('导入成功')
    load()
  } else {
    ElMessage.error(res.msg)
  }
}

const handleFileSuccess = (res) => {

  data.form.avatar=res.data
  // console.log(res.data)
}

</script>
